package com.example.opengl.egl

import android.view.Surface
import com.alibaba.android.arouter.facade.annotation.Route
import com.android.baselibrary.base.BaseActivity
import com.android.baselibrary.video.VideoExt
import com.example.opengl.R
import com.example.opengl.databinding.ActivityEglRenderVideoBinding
import com.example.opengl.main.OpenGLPath
import com.example.opengl.main.OpenGlMainActivity
import com.example.opengl.player.base.*
import com.example.opengl.player.decoder.AudioDecoder
import com.example.opengl.player.decoder.VideoDecoder
import com.example.opengl.render.video.VideoDrawer
import java.util.concurrent.Executors

/**
 * EGL渲染视频
 */
@Route(path = OpenGLPath.OPENGL_RENDER_EGL)
class EGLRenderActivity:BaseActivity<ActivityEglRenderVideoBinding>() {
    override fun getLayoutId(): Int  = R.layout.activity_egl_render_video
    private val threadPool = Executors.newFixedThreadPool(10)
    override fun initView() {
        val videoInfo =  VideoExt.getVideoInfo(OpenGlMainActivity.VIDEO_PATH)

        val  videoDrawer = VideoDrawer()
         val render = CustomerGLRender(videoDrawer)
        render.setSurface(mBinding.surface)
        videoDrawer.setVideoSize(videoInfo.width,videoInfo.height)
        videoDrawer.getSurfaceTexture {
           initPlayer(videoInfo.path,Surface(it),render)
        }
    }
    private fun initPlayer(videoPath: String, surface: Surface, render: CustomerGLRender){
       val videoDecoder =  VideoDecoder(videoPath,surface)
        threadPool.execute(videoDecoder)
        videoDecoder.setStateListener(object : DefDecoderStateListener{
            override fun decodeOneFrame(decodeJob: BaseDecoder?, frame: Frame) {
                super.decodeOneFrame(decodeJob, frame)
                render.notifySwap(frame.bufferInfo.presentationTimeUs)
            }
        })
        val audioDecoder = AudioDecoder(videoPath)
        threadPool.execute(audioDecoder)
        videoDecoder.goOn()
        audioDecoder.goOn()
    }

    override fun initListener() {

    }

    override fun onDestroy() {
        super.onDestroy()
        threadPool.shutdownNow()
    }
}